package sql

import (
	"strings"
)

func (sqlOper *SqlOper) ParseCreate(one string) {
	fields := strings.Split(one, "\n")
	name := sqlOper.ParseTableName(strings.Fields(fields[0])[2])

	// sqlOper.Tables[name] = []string{}
	tableKeys := make(map[string]string)
	oneHead := []string{}
	for _, item := range fields[1 : len(fields)-1] {
		subFields := strings.Fields(item)
		if len(subFields) > 1 && strings.HasPrefix(subFields[0], "`") {
			itemName := subFields[0][1:]
			itemName = itemName[:len(itemName)-1]
			itemTp := subFields[1]
			tableKeys[itemName] = itemTp
			oneHead = append(oneHead, itemName+"::"+itemTp)
		} else if item == ")" {
			break
			// log.Fatal(item)
		}

	}
	sqlOper.Tables[name] = tableKeys
	sqlOper.Heads[name] = oneHead
}

func (sqlOper *SqlOper) SetFilterTable(tbs ...string) {
	for _, t := range tbs {
		sqlOper.FilterTables[t] = true
	}

}

func (sqlOper *SqlOper) FilterTable(tb string) bool {
	if len(sqlOper.FilterTables) == 0 {
		return true
	}
	if _, ok := sqlOper.FilterTables[tb]; ok {
		return true
	}
	return false
}

func (sqlOper *SqlOper) ParseOneBracketValues(one string) (out []string) {
	oneS := strings.TrimSpace(one)
	if oneS[0] == '(' {
		oneS = oneS[1 : len(oneS)-1]
	}

	for _, v := range SplitAtCommas(oneS) {
		if len(v) == 0 {
			out = append(out, "")
			// log.Fatal("Err parse bracket:", one)
		}
		if v[0] == '`' {
			out = append(out, v[1:len(v)-1])
		} else {
			out = append(out, v)
		}
	}
	return
}

func (sqlOper *SqlOper) GetTables() (names []string) {

	for t := range sqlOper.Tables {
		names = append(names, t)

	}
	return
}
